package helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.primefaces.model.UploadedFile;

public class UploadFile {

    public static String uploadfile(UploadedFile file, String path) {
        String filename = "";
        if (file != null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            filename = sdf.format(new Date()) + file.getFileName();
            ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
            File result = new File(extContext.getRealPath(path + filename));
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(result);
                byte[] buffer = new byte[6124];
                int bulk;
                InputStream inputStream = file.getInputstream();
                while (true) {
                    bulk = inputStream.read(buffer);
                    if (bulk < 0) {
                        break;
                    }
                    fileOutputStream.write(buffer, 0, bulk);
                    fileOutputStream.flush();
                }
                fileOutputStream.close();
                inputStream.close();
            } catch (IOException e) {
            }
        }
        return filename;
    }
}
